package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"lz/global"
	"lz/utils"
	"net/http"
	"strings"
)

func HandleValidator(err error, c *gin.Context) {

	//这里绑定到gin的validator
	errs, ok := err.(validator.ValidationErrors)
	if !ok {
		utils.GinError(c, errs, "服务异常", http.StatusOK)
		return
	}
	for _, v := range RemoveTopStruct(errs.Translate(global.Tsrans)) {

		utils.GinError(c, errs, v, http.StatusBadRequest)
		return

	}
	return
}

func RemoveTopStruct(fileds map[string]string) map[string]string {

	rsp := map[string]string{}
	for field, err := range fileds {
		rsp[field[strings.Index(field, ".")+1:]] = err
	}
	return rsp

}

func HandleGrpcErrorToHttp(err error, c *gin.Context) {

	//如果grpc报错
	if err != nil {

		if e, ok := status.FromError(err); ok {
			switch e.Code() {
			case codes.NotFound:
				utils.GinError(c, err, e.Message(), http.StatusNotFound)
			case codes.Internal:
				utils.GinError(c, err, "服务器内部错误", http.StatusInternalServerError)
			case codes.InvalidArgument:
				utils.GinError(c, err, e.Message(), http.StatusBadRequest)
			case codes.Unavailable:
				utils.GinError(c, err, "用户服务不可用", http.StatusInternalServerError)
			case codes.AlreadyExists:
				utils.GinError(c, err, e.Message(), http.StatusBadRequest)
			default:
				utils.GinError(c, err, e.Message(), http.StatusInternalServerError)
			}
			return
		}
	}
}
